package net.apexes.demo.codegen.util;

import com.j256.ormlite.jdbc.DataSourceConnectionSource;
import com.j256.ormlite.jdbc.db.H2DatabaseType;
import com.j256.ormlite.support.ConnectionSource;
import net.apexes.commons.guice.tx.TxConnection;

import javax.sql.DataSource;
import java.io.File;
import java.net.URL;
import java.sql.Connection;

/**
 * @author hedyn
 */
public class DemoDatabases {
    private DemoDatabases() {}

    public static Connection createConnection() throws Exception {
        URL url = DemoDatabases.class.getResource("/demo.sql");
        return SourceDatabaseCreator.h2database("demo").forResource(new File(url.getFile()));
    }

    public static DataSource createDataSource() throws Exception {
        Connection conn = new TxConnection(createConnection());
        return new DemoDataSource(conn);
    }

    public static ConnectionSource createConnectionSource() throws Exception {
        DataSourceConnectionSource source = new DataSourceConnectionSource();
        source.setDataSource(createDataSource());
        source.setDatabaseType(new H2DatabaseType());
        source.initialize();
        return source;
    }

}
